package com.finger.forest.ui.monitor;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.finger.forest.R;
import com.finger.forest.adapter.MonitorRightAdapter;
import com.finger.forest.base.BaseFragment;
import com.finger.forest.base.BaseView;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.RequestUtil;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.UniversalItemDecoration;
import com.google.gson.JsonObject;
import com.jakewharton.rxbinding2.view.RxView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 监控
 */
public class MonitorFragment extends BaseFragment<RegisterPresenter> implements BaseView {

    private static final String TAG = "MonitorFragment";

    private Unbinder unbinder;

    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.ivTop)
    ImageView ivTop;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.ivBottom)
    ImageView ivBottom;
    @BindView(R.id.ivReset)
    ImageView ivReset;
    @BindView(R.id.ivPlay)
    ImageView ivPlay;
    @BindView(R.id.ivMenuRight)
    ImageView ivMenuRight;

    @BindView(R.id.dlContent)
    DrawerLayout dlContent;

    @BindView(R.id.tvReset)
    TextView tvReset;
    @BindView(R.id.tvFocusIn)
    TextView tvFocusIn;
    @BindView(R.id.tvFocusOut)
    TextView tvFocusOut;
    @BindView(R.id.tvZoomIn)
    TextView tvZoomIn;
    @BindView(R.id.tvZoomOut)
    TextView tvZoomOut;

    @BindView(R.id.rvMore)
    RecyclerView rvMore;

    private MonitorRightAdapter monitorRightAdapter;

    private List<String> titles = new ArrayList<>();

    @BindView(R.id.web_view_vedio)
    WebView vedioWebView;

    private String channelNum;
    private String lUser;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_monitor, container, false);
        unbinder = ButterKnife.bind(this, root);
        return root;
    }

    @Override
    protected void receiveData() {
        titles.add("http://192.168.1.231:18000/flv/hls/stream_3_0.flv");
    }

    @Override
    protected void initializeNavigation() {

    }

    @Override
    protected void initializeView() {

        //设置WebView
        vedioWebView.setWebViewClient(new WebViewClient());

        WebSettings setting = vedioWebView.getSettings();
        setting.setUseWideViewPort(true);
        setting.setLoadWithOverviewMode(true);
        // 设置与Js交互的权限
        setting.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        setting.setJavaScriptCanOpenWindowsAutomatically(true);
        //自适应屏幕
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setLoadWithOverviewMode(true);

        String URL = "file:///android_asset/index.html";
        // 先载入JS代码
        // 格式规定为:file:///android_asset/文件名.html
        vedioWebView.loadUrl(URL);


        monitorRightAdapter = new MonitorRightAdapter(R.layout.monitor_right_item_view, titles);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        rvMore.setLayoutManager(linearLayoutManager);
        rvMore.setAdapter(monitorRightAdapter);

        rvMore.addItemDecoration(new UniversalItemDecoration() {
            @Override
            public Decoration getItemOffsets(int position) {
                ColorDecoration decoration = new ColorDecoration();
                decoration.bottom = getResources().getDimensionPixelOffset(R.dimen.dp_1);
                decoration.decorationColor = ContextCompat.getColor(getContext(), R.color.blackF5);
                return decoration;
            }
        });

        monitorRightAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ToastUtils.show("监控切换成功");
                dlContent.closeDrawer(Gravity.END);
                handlePlay();
            }
        });

        clicks();

        //关闭WebView滚动
        vedioWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        //监控视频登录
        vedioLogin();
    }

    /**
     * 监控视频登录
     */
    private void vedioLogin(){
        String vedioLoginUrl = "http://192.168.1.240/prod-api/surveillance/hkSdk/login?ip=192.168.1.63&port=8000&userName=admin&password=ahly12345";
        //海康视频监控登录
        RequestUtil.httpGet(vedioLoginUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG,"海康视频登录失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();//得到返回的数据
                Log.i(TAG,"海康视频登录成功："+result);
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject.get("code")!=null && jsonObject.get("code").toString().equals("500")){
                    ToastUtils.show("海康视频登录失败："+jsonObject.get("msg").toString());
                } else {
                    JSONObject jsonObj = JSON.parseObject(jsonObject.get("data").toString());
                    channelNum = jsonObj.get("iChannelNum").toString();
                    lUser = jsonObj.get("lUser").toString();
                }
            }
        });
    }

    /**
     * 控制摄像头方向
     * @param type
     */
    private void vedioControl(String type){
        String vedioControlUrl = "http://192.168.1.240/prod-api/surveillance/hkSdk/controlViewAtHIKSDK" +
                "?lUser="+lUser+"&channelNum="+channelNum+"&type="+type;
        //海康视频监控登录
        RequestUtil.httpGet(vedioControlUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG,"海康视频控制失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();//得到返回的数据
                Log.i(TAG,"海康视频控制成功："+type);
            }
        });
    }

    @SuppressLint("WrongConstant")
    private void clicks() {
        //左边按钮
        RxView.clicks(ivLeft).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("左移动");
            vedioControl("left");
        });

        //上边按钮
        RxView.clicks(ivTop).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("上移动");
            vedioControl("up");
        });

        //右边按钮
        RxView.clicks(ivRight).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("右移动");
            vedioControl("right");
        });

        //下边按钮
        RxView.clicks(ivBottom).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("下移动");
            vedioControl("down");
        });

        //刷新
        RxView.clicks(ivReset).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("刷新");
            handlePlay();
        });

        //刷新
        RxView.clicks(tvReset).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("刷新");
            vedioWebView.loadUrl("javascript:playUrl()");
        });

        //近焦
        RxView.clicks(tvFocusIn).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("近焦");
            vedioControl("focusIn");
        });

        //远焦
        RxView.clicks(tvFocusOut).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("远焦");
            vedioControl("focusOut");
        });

        //放大
        RxView.clicks(tvZoomIn).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("放大");
            vedioControl("zoomOut");
        });

        //缩小
        RxView.clicks(tvZoomOut).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            ToastUtils.show("缩小");
            vedioControl("zoomIn");
        });

        //播放
        RxView.clicks(ivPlay).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            handlePlay();
        });

        //菜单
        RxView.clicks(ivMenuRight).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            dlContent.openDrawer(Gravity.END);
        });
    }

    private void handlePlay(){
        //隐藏播放按钮
        ivPlay.setVisibility(View.INVISIBLE);
        // 通过Handler发送消息，调js播放方法
        vedioWebView.post(new Runnable() {
            @Override
            public void run() {

                // 注意调用的JS方法名要对应上
                // 调用javascript的callJS()方法
                vedioWebView.loadUrl("javascript:playUrl()");
            }
        });
    }

    @Override
    protected void loadDataFromServer() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != unbinder) {
            unbinder.unbind();
        }
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }
}